package com.system.service.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.Enums.ResponseEnum;
import com.common.exception.CourseException;
import com.common.util.CopyUtil;
import com.common.util.UuidUtil;
import com.core.system.domain.Resource;
import com.core.system.mapper.ResourceMapper;
import com.core.system.service.imp.ResourceServiceImp;
import com.system.dto.ResourceDto;
import com.system.mapper.ResourceExMapper;
import com.system.service.ResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.common.Enums.ResponseEnum.*;



@Service
@Slf4j
@Primary
public class ResourceExServiceImp   extends ResourceServiceImp implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceExMapper resourceExMapper;

    /**
     * 保存，id有值时更新，无值时新增
     */
    @Override
    public ResponseEntity save(com.core.system.dto.ResourceDto resourceDto) {
        Resource resource = CopyUtil.copy(resourceDto, Resource.class);
        if(StringUtils.isEmpty(resource.getId())) {
            resource.setId(resource.getParent() + resource.getSort());
        }
        if (StringUtils.isEmpty(resourceDto.getId())) {
           return this.insert(resource);
        } else {
            return this.update(resource);
        }

    }
    /**
     * 更新
     */
    private ResponseEntity update(Resource resource) {
        int i = resourceMapper.updateById(resource);
        if(i<=0){
            throw new CourseException(ResponseEnum.UPDATE_ERROR);
        }
        return ResponseEntity.ok(UPD_SUCCESS.getDesc());
    }
    /**
     * 新增
     */
    private ResponseEntity insert(Resource resource) {
        resource.setId(UuidUtil.getShortUuid());
        int i = resourceMapper.insert(resource);
        if(i<=0){
            throw new CourseException(ResponseEnum.ADD_ERROR);
        }
        return ResponseEntity.ok(ADD_SUCCESS.getDesc());
    }

    /**
     * 保存资源树
     * @param json
     */
    @Transactional
    public ResponseEntity saveJson(String json) {
        List<ResourceDto> jsonList = JSON.parseArray(json, ResourceDto.class);
        log.info(JSON.toJSONString(jsonList,true));
        List<ResourceDto> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(jsonList)) {
            for (ResourceDto d: jsonList) {
                d.setParent("");
                add(list, d);
            }
        }
        log.info("共{}条", list.size());
        resourceMapper.delete(null);
        int i = resourceExMapper.insertResourseList(list);
        if(i<0){
            throw new CourseException(ResponseEnum.UPDATE_ERROR);
        }
        return  ResponseEntity.ok().body(SUCCESS.getDesc());

    }
    /**
     * 递归，将树型结构的节点全部取出来，放到list
     * @param list
     * @param dto
     */
    public void add(List<ResourceDto> list, ResourceDto dto) {
        list.add(dto);
        if (!CollectionUtils.isEmpty(dto.getChildren())) {
            for (ResourceDto d: dto.getChildren()) {
                d.setParent(dto.getId());
                add(list, d);
            }
        }
    }
    /**
     * 按约定将列表转成树
     * 要求：ID要正序排列
     * @return
     */
    public ResponseEntity loadTree(Resource resource) {
        List<Resource> resourceList = resourceMapper.selectList(
                new LambdaQueryWrapper<Resource>(resource)
                        .orderBy(true,true,Resource::getId));
        List<ResourceDto> resourceDtoList = CopyUtil.copyList(resourceList, ResourceDto.class);
        for (int i = resourceDtoList.size() - 1; i >= 0; i--) {
            // 当前要移动的记录
            ResourceDto child = resourceDtoList.get(i);
            // 如果当前节点没有父节点，则不用往下了
            if (StringUtils.isEmpty(child.getParent())) {
                continue;
            }
            // 查找父节点
            for (int j = resourceDtoList.size() - 1; j >= 0; j--) {
                ResourceDto parent = resourceDtoList.get(j);
                if (child.getParent().equals(parent.getId())) {
                    if (CollectionUtils.isEmpty(parent.getChildren())) {
                        parent.setChildren(new ArrayList<>());
                    }
                    // 添加到最前面，否则会变成倒序，因为循环是从后往前循环的
                    if(!parent.getChildren().contains(child)) {
                        parent.getChildren().add(0, child);

                    }
                    if(parent.getChildren().size()>=2) {
                        Collections.sort(parent.getChildren(), Comparator.comparing(ResourceDto::getSort));//排序默认升序
                    }
                    // 子节点找到父节点后，删除列表中的子节点
//                    resourceDtoList.remove(child);
                }
            }

        }
        List<ResourceDto>resourceDtoList1=new ArrayList<>();
        for (int i = 0; i <resourceDtoList.size() ; i++) {
            if(StringUtils.isEmpty(resourceDtoList.get(i).getParent())){
                resourceDtoList1.add(resourceDtoList.get(i));
            }
        }
        resourceDtoList.clear();
        if(!CollectionUtils.isEmpty(resourceDtoList1)) {
            Collections.sort(resourceDtoList1, Comparator.comparing(ResourceDto::getSort));
        }
        return ResponseEntity.ok(resourceDtoList1);
    }
}
